import './index.scss';
import tpl from './index.tpl';
import { CartModel } from '../../../models/cart';
import CheckBox from '../check_box/index';
import NumSelector from '../num_selector/index';
import Toast from '../../toast/index';

const cartModel = new CartModel,
  checkBox = new CheckBox(),
  numSelector = new NumSelector(),
  toast = new Toast();

export default () => {
  return {
    name: 'cartListItem',
    tpl,
    makeList(data) {
      let list = '';

      data.forEach((elem, index) => {
        elem.checked = true;
        list += tpl().replace(/{{(.*?)}}/g, (node, key) => {
          return {
            goods_name: elem.goods_name,
            img_url: elem.img_url,
            price: elem.price,
            id: elem.id,
            index: index,
            check_box: checkBox.tpl(elem.id, 'subCheck', index),
            num_selector: numSelector.tpl(elem.id, elem.num, index, elem.limitation)
          }[key];
        });
      });
      return list;
    },

    listEvent(e) {
      let tar = e.target || e.srcElement,
        className = tar.className,
        oParent = tar.parentNode;

      return new Promise((resolve, reject) => {
        if (className === 'item btn') {
          const field = tar.dataset.field,
            id = oParent.dataset.id,
            index = oParent.dataset.index,
            limitation = parseInt(tar.dataset.limitation),
            oInput = document.getElementById('J_numInput_' + id);
          switch (field) {
            case 'add':
              if (parseInt(oInput.value) < limitation) {
                oInput.value = parseInt(oInput.value) + 1;
                //计算总价
                cartModel.updateCartNum(id, oInput.value);
                //resolve返回修改
                resolve({ field: 'numSelector', num: oInput.value, id });
                // this.updateCartNum(id, oInput.value, resolve);
              } else {
                resolve(-1);
              }
              break;
            case 'minus':
              if (parseInt(oInput.value) > 1) {
                oInput.value = parseInt(oInput.value) - 1;
                //totalPrice
                cartModel.updateCartNum(id, oInput.value);
                //changeNumber
                resolve({ field: 'numSelector', num: oInput.value, id });
                // this.updateCartNum(id, oInput.value, resolve);
              } else {
                resolve(-1);
              }
              break
            default:
              break;
          }

        //check funciton
        } else if (className === 'check-input J_subCheck' || className === 'fa fa-check') {

          const oParent = tar.parentNode,
            id = oParent.dataset.id,
            oSubChecks = Array.from(document.getElementsByClassName('J_subCheck')),
            idx = oSubChecks.indexOf(tar),
            checked = oSubChecks[idx].checked, //target checked status
            oMainCheck = document.getElementsByClassName('J_mainCheck')[0]; //check all checkInput

          oMainCheck.checked = oSubChecks.every((elem) => {
            return elem.checked === true; //boolean true
          });
          resolve({ field: 'checkBox', id, checked });
          
        } else if (className === 'fa fa-trash') {
          const id = tar.dataset.id,
            idx = tar.dataset.index,
            oDeleteItem = tar.parentNode.parentNode;

          cartModel.removeCartItem(id).then((res) => {
            const code = res.msg_code;
            if (code === '200') {
              toast.showToast({
                icon: 'success',
                title: '删除成功'
              });

              resolve({ field: 'remove', id }); //resolve and delete cartInfos data
              oDeleteItem.remove(); //delete dom node
            } else {
              toast.showToast({
                icon: 'warning',
                title: '删除失败'
              })
            }
          });
        } else {
          resolve(-1); //此处要resolve一个值，不然.then方法无法调用
        }
      })
    }

  }
}